package net.maku.kyy.controller;


import cn.hutool.core.util.RandomUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import net.maku.api.module.system.SmsApi;
import net.maku.framework.common.utils.Result;
import net.maku.framework.security.utils.TokenUtils;
import net.maku.kyy.dto.KyyLoginDTO;
import net.maku.kyy.dto.KyyUserPasswordLoginDTO;
import net.maku.kyy.service.KyyUserLoginService;
import net.maku.kyy.vo.KyyUserTokenVO;
import net.maku.tencentsms.service.TencentSmsService;
import org.apache.el.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;


/**
 * 应用登录
 */
@Slf4j
@RestController
@RequestMapping("/kyy/login")
public class KyyUserLoginController {

    @Autowired
    private KyyUserLoginService kyyLoginService;

    @Autowired
    private TencentSmsService tencentSmsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private TencentSmsService smsApi;

    /**
     * 账号/手机号密码登录
     * @param kyyUserPasswordLoginDTO
     * @return
     */
    @PostMapping("/password")
    public Result<String> passwordLogin(@RequestBody KyyUserPasswordLoginDTO kyyUserPasswordLoginDTO){
//        log.info("密码登录：{}",kyyUserPasswordLoginDTO);
        KyyUserTokenVO tokenVO=kyyLoginService.passwordLogin(kyyUserPasswordLoginDTO);
        return Result.ok(tokenVO.getAccessToken());
    }

    /**
     * 手机号验证码登录
     * @param kyyLoginDTO
     * @return
     */
    @PostMapping("/codelogin")
    public Result<String> codeLogin(@RequestBody KyyLoginDTO kyyLoginDTO){
//        log.info("手机号验证码登录：{}",kyyLoginDTO);
        KyyUserTokenVO tokenVO=kyyLoginService.codeLogin(kyyLoginDTO);
        log.info("登录成功：{}",tokenVO);
        return Result.ok(tokenVO.getAccessToken());
    }

    /**
     * 微信登录
     * @param code
     * @return
     */
    @GetMapping("/wechat/{code}")
    public Result<String> wechatLogin(@PathVariable("code") String code){
//        log.info("微信登录：code={}",code);
        KyyUserTokenVO tokenVO=kyyLoginService.wechatLogin(code);
        return Result.ok(tokenVO.getAccessToken());
    }


    /**
     * 退出登录
     * @return
     */
    @PostMapping("/logout")
    @PreAuthorize("hasAuthority('kyy:user')")
    public Result<String> logout(HttpServletRequest request){
        kyyLoginService.logout(TokenUtils.getAccessToken(request));
        return Result.ok();
    }


    /**
     * 发送登录验证码
     * @param phone 手机号
     * @return
     */
    @PostMapping("/sendcode/{phone}")
    public Result sendCode(@PathVariable("phone")String phone) {

        // 生成6位数字验证码
        String code = RandomUtil.randomNumbers(6);

        try {
            redisTemplate.opsForValue().set("kyy:login:code:" + phone, code, 5, TimeUnit.MINUTES);
            System.out.println("Redis连接测试成功，获取的值: ");
            smsApi.sendSms(phone, new String[]{code});
        } catch (Exception e) {
            System.err.println("Redis连接失败: " + e.getMessage());
        }
        System.out.println("验证码发送成功，验证码：" + code);
        return Result.ok();
    }
}
